package cn.qiyu5522.serializers;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * @BelongsProject: tk_ems
 * @BelongsPackage: cn.qiyu5522.tk_ems.serializer
 * @Author: TangQi
 * @CreateTime: 2023-02-08  09:23
 * @Description: TODO
 * @Version: 1.0
 */
/*
序列化
 */
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

    private static final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)
            throws IOException {
        long timestamp = p.getValueAsLong();
        if (timestamp > 0) {
            return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
        } else {
            //兼容字符串格式时间传入
            String value = p.getValueAsString();
            return LocalDateTimeUtil.of(DateUtil.parse(value));
        }
    }

}
